package com.hlkj.pay.util;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.math.BigInteger;
import java.nio.charset.StandardCharsets;
import java.util.Base64;

public class AESUtils {

    private static final String secret_key = "1234567890123456"; // AES 密钥长度为16字节（128位）

    public static String encrypt(String data) throws Exception {
        return encrypt(data, secret_key);
    }

    // AES加密
    public static String encrypt(String data, String key) throws Exception {
        // 创建密钥
        SecretKeySpec secretKey = new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), "AES");

        // 创建Cipher对象，指定AES加密模式
        Cipher cipher = Cipher.getInstance("AES");

        // 初始化Cipher对象为加密模式
        cipher.init(Cipher.ENCRYPT_MODE, secretKey);

        // 执行加密操作
        byte[] encryptedBytes = cipher.doFinal(data.getBytes(StandardCharsets.UTF_8));

        // 使用Base64编码加密后的字节数据，返回加密后的字符串
        return Base64.getEncoder().encodeToString(encryptedBytes);
    }

    // AES解密
    public static String decrypt(String encryptedData, String key) {
        try {
            // 创建密钥
            SecretKeySpec secretKey = new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), "AES");

            // 创建Cipher对象，指定AES解密模式
            Cipher cipher = Cipher.getInstance("AES");

            // 初始化Cipher对象为解密模式
            cipher.init(Cipher.DECRYPT_MODE, secretKey);

            // 将Base64编码的加密数据解码为字节数组
            byte[] decodedBytes = Base64.getDecoder().decode(encryptedData);

            // 执行解密操作
            byte[] decryptedBytes = cipher.doFinal(decodedBytes);

            // 将解密后的字节数据转换为字符串并返回
            return new String(decryptedBytes, StandardCharsets.UTF_8);
        } catch (Exception e) {
            return "";
        }
    }

    public static String decrypt(String data) throws Exception {
        return decrypt(data, secret_key);
    }

    public static void main(String[] args) {
        try {
            String data = "APP_8428691003";

            // 加密
            String encryptedData = encrypt(data);
            System.out.println("Encrypted Data (Only letters and numbers, Base36): " + encryptedData);

            // 解密
            String decryptedData = decrypt(encryptedData);
            System.out.println("Decrypted Data: " + decryptedData);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
